import { useEffect, useState } from 'react'
import './index.scss'

function SelectGoods({ goods, onSelectGoods }) {
  const [selectedGoods, setSelectGoods] = useState()
  const [index, setIndex] = useState(0)

  useEffect(() => {
    if (goods) {
      setSelectGoods(goods?.item?.skus[index])
      onSelectGoods(goods?.item?.skus[index]);
    }
  }, [goods]);

  const selectGoods = (index) => {
    const selectedGoods = goods?.item?.skus[index];
    setSelectGoods(selectedGoods);
    setIndex(index);
    onSelectGoods(selectedGoods);
  }

  const pre = () => {
    if (index <= 0) return;
    selectGoods(index - 1);
  }

  const next = () => {
    if (index >= goods?.item?.skus.length - 1) return;
    selectGoods(index + 1);
  }

  return (
    <div className='select-goods'>
      <img className='goods-img' alt='good img' src={selectedGoods?.preview_img_urls[0]} />
      <div className='scroll-view'>
        <img className='pre-icon' alt='pre' src={require('../../assets/pre.png')} onClick={pre} />
        <div className='goods-all'>
          {
            goods?.item?.skus.map((sku, index) => {
              return (
                <div className={`goods-item ${sku.sku_no === selectedGoods?.sku_no ? 'active' : ''}`} key={sku.sku_no} onClick={() => selectGoods(index)}>
                  <img className='goods-thum' alt='goods thum' src={sku.preview_img_urls[0]} />
                </div>
              )
            })
          }
        </div>
        <img className='next-icon' alt='next' src={require('../../assets/next.png')} onClick={next} />
      </div>
    </div>
  )
}

export default SelectGoods